<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\App;
use think\facade\View;

class Relation extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\User';

    public function index()
    {
        $keyword = $this->request->param('keyword');
        if ($keyword) {
            $map['code|nickname|mobile'] = $keyword;
        } else {
            $map['parent_id'] = 0;
        }
        $map['is_del'] = 0;
        $list = $this->model::where($map)->field('id,code,nickname,mobile,level_id')
            ->order('is_active desc,active_time asc,id desc')->select();
        foreach ($list as &$v) {
            $level = $v->level ? $v->level->title : '无';
            $v['title'] = '编号【' . $v['code'] . '】
                姓名【' . $v->nickname . '】
                手机号【' . $v->mobile . '】
                等级【' . $level . '】
              ';
        }
        View::assign('list', $list);

        return View::fetch();
    }

    public function getData()
    {
        try {
            $id = $this->request->param('id');
            $list = $this->model::field('id,code,nickname,mobile,level_id')
                ->where(['parent_id' => $id, 'is_del' => 0])->order('is_active desc,active_time asc,id desc')->select();
            foreach ($list as &$v) {
                $level = $v->level ? $v->level->title : '无';
                $v['title'] = '用户名【' . $v['code'] . '】
                    昵称【' . $v->nickname . '】
                    手机号【' . $v->mobile . '】
                    等级【' . $level . '】
                  ';
            }

        } catch (\Exception $e) {

            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => 'success', 'result' => $list]);
    }
}